package hospital.oss.service.Impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import hospital.oss.service.FileService;
import hospital.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author
 * @description:
 */
@Service
public class FileServiceImpl implements FileService {
    /**
     * @return
     * @Author yang
     * @Description //TODO //上传文件到阿里云oss
     * @Param [file]
     **/
    @Override
    public String fileUpload(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConstantOssPropertiesUtils.ENPOINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConstantOssPropertiesUtils.BUKET;
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = null;
        //得到文件的原始名字
        objectName = file.getOriginalFilename();
        //生成随机唯一值，使用uuid，添加到文件名称里面，防止相同文件名导致文件覆盖，因为用户上传的文件名可能会一致
        //把生成的uuid里面的-替换掉
        String uuid = UUID.randomUUID().toString().replace("-", "");
        objectName = uuid + objectName;
        //按照当前日期，创建文件夹2021/02/02/，上传到创建的文件夹里面, 结果形式为：2021/02/02/uuid01.jpg。
        //因为前面引入了依赖joda-time，所以转日期可以直接.toString("yyyy/MM/dd")
        String timeUrl = new DateTime().toString("yyyy/MM/dd");
        // 2022/09/27/4fbadcac84ae4e518098fa32574d79caa2.png
        objectName = timeUrl + "/" + objectName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);

            //上传之后文件路径  格式要和阿里云上面的一致
            // https://violetiii.oss-cn-beijing.aliyuncs.com/2022/09/27/4fbadcac84ae4e518098fa32574d79caa2.png
            String url = "https://" + bucketName + "." + endpoint + "/" + objectName;

            // 关闭OSSClient。
            ossClient.shutdown();

            return url;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    @Override
    public String upload(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        // Endpoint = oss-cn-beijing.aliyuncs.com 会导致[Client]Unable to execute HTTP request: SocketException
        String endpoint = ConstantOssPropertiesUtils.ENPOINT;
        // 解决办法给地域节点上，加上 https://
        String HttpsEndpoint = "https://"+endpoint;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUKET;
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(HttpsEndpoint, accessKeyId, accessKeySecret);
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl + "/" + fileName;

            //调用方法实现上传
            // 1.jpg    /a/b/1.jpg

            // 上传文件的时候出现错误 Unable to execute HTTP request: SocketException
            // 因为 endpoint 出现问题，少了 https://
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //上传之后文件路径
            // https://violetiii.oss-cn-beijing.aliyuncs.com/2023/05/10/c8dda75d0956421f8e75effa9a2bbacea4.png
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            //返回
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
